package com.cc.service.impl;

import com.cc.entity.UserInfo;
import com.cc.mapper.UserInfoMapper;
import com.cc.service.IUserInfoService;
import com.cc.utils.SqlSessionUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//业务层
@Component
public class UserInfoServiceImpl1 implements IUserInfoService {
    @Autowired(required = false)
    private UserInfoMapper userInfoMapper;

    /**
     * 转账业务：旺财（from）转账给来福(to)，转money钱
     * <p>
     * 旺财（from） 更新操作 减money 来福 （to） 更新操作 加money= money +钱
     * <p>
     * zz(1,2,300)
     * <p>
     * 返回值： true 转账成功 false 转账失败
     */
    public boolean zz(int from, int to, int money) {
        return zzOptional(from, to, money);
    }

    private boolean zzOptional(int from, int to, int money) {
        SqlSession sqlSession = SqlSessionUtils.openSession();
        System.out.println("sqlSession===>" + sqlSession);
        userInfoMapper = sqlSession.getMapper(UserInfoMapper.class);
        // 一,==============旺财的钱减少300==============
        // 1.1查询旺财有多少钱
        UserInfo wc = userInfoMapper.selectByPrimaryKey(from);
        System.out.println(wc);
        // 1.2扣旺财有300
        int result = 0;
        if (wc != null) {
            wc.setMoney(wc.getMoney() - money);
            result = userInfoMapper.updateByPrimaryKey(wc);
        }
        // ==============二,来福的钱增加300==============
        // 1.1查询旺财有多少钱
        UserInfo lf = userInfoMapper.selectByPrimaryKey(to);
        System.out.println(lf);
        // 1.2扣旺财有300
        int result2 = 0;
        if (lf != null) {
            lf.setMoney(lf.getMoney() + money);
            result2 = userInfoMapper.updateByPrimaryKey(lf);
        }
        // ==============最后的结果==============
        if (result > 0 && result2 > 0) {
            System.out.println("转账成功！！");
            //sqlSession.commit();//提交事务
            return true;// 转账成功
        } else {
            //sqlSession.rollback();//回滚事务
            System.out.println("转账失败！！");
            return false;
        }
    }
}






















